package com.bdsoft.actions.menuManage.Service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.bdsoft.actions.menuManage.Dao.MenuMapper;
import com.bdsoft.actions.menuManage.DTO.MenuDTO;
import com.bdsoft.actions.menuManage.Service.MenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Map<String,Object>> getMenuList() {

        List<Map<String,Object>> resList = menuMapper.selectMenuByParams();
        return resList;
    }

    @Override
    public Map<String, Object> allocateMenu(String roleId, String menuIds) {
        List<String> menuIdList= StrUtil.split(menuIds,",");
       menuMapper.DeleteMenuRole(roleId);

        for (String s:menuIdList){

            menuMapper.InsertMenuRole(roleId,s);
        }





        return  MapUtil.<String,Object>builder()
                .put("code", 200)
                .put("data", "分配菜单成功")
                .build();

    }

    @Override
    public int addMenu(MenuDTO menu) {
        UUID uuid=UUID.randomUUID();
        menu.setMenuId(uuid.toString());
        return menuMapper.insertMenu(menu);
    }

    @Override
    public int updateMenu(MenuDTO menu) {
        return menuMapper.updateMenu(menu);
    }

    @Override
    public int deleteMenu(String menuId) {
        return menuMapper.deleteMenu(menuId);
    }

    @Override
    public  Map<String,Object>  getMenuById(String menuId) {
        return MapUtil.<String,Object>builder()
                .put("code", 200)
                .put("data", menuMapper.selectMenuById(menuId))
                .build();
    }

    @Override
    public Map<String, Object> getMenuListLeft() {
        List<Map<String,Object>> menuStore=menuMapper.selectMenuByParams();

        Collection<? extends GrantedAuthority> authorities =
                SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        Set<String> perms = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toSet());
        List<Map<String,Object>> userMenus = menuStore.stream()
                .filter(menu -> perms.contains(menu.get("permission")))
                .collect(Collectors.toList());

        List<Map<String,Object>> tree=buildMenuTree(menuStore);
        return MapUtil.<String,Object>builder()
                .put("code", 200)
                .put("data", tree)
                .build();
    }

    @Override
    public Map<String, Object> allocateMenuByMenu(String menuId, String roleIds) {
        List<String> menuIdList= StrUtil.split(roleIds,",");



        for (String s:menuIdList){

            menuMapper.InsertMenuRole(s,menuId);
        }





        return  MapUtil.<String,Object>builder()
                .put("code", 200)
                .put("data", "分配菜单成功")
                .build();

    }

    @Override
    public Map<String, Object> findRoleByMenu(String menuId) {



        return MapUtil.<String,Object>builder()
                .put("code", 200)
                .put("data", menuMapper.selectRoleById(menuId))
                .build();
    }

    public static List<Map<String, Object>> buildMenuTree(List<Map<String, Object>> flatMenus) {
        // 用Map存储所有菜单（按menu_id索引）
        Map<String, Map<String, Object>> menuMap = new HashMap<>();

        // 初始化所有菜单节点，并添加children占位
        for (Map<String, Object> menu : flatMenus) {
            menu.put("children", new ArrayList<>());
            menuMap.put((String) menu.get("menu_id"), menu);
        }

        // 构建树形结构
        List<Map<String, Object>> tree = new ArrayList<>();
        for (Map<String, Object> menu : flatMenus) {
            String parentId = (String) menu.get("parent_id");
            if ("-1".equals(parentId)) {
                // 顶级菜单
                tree.add(menu);
            } else {
                // 子菜单：添加到父菜单的children中
                Map<String, Object> parent = menuMap.get(parentId);
                if (parent != null) {
                    ((List<Map<String, Object>>) parent.get("children")).add(menu);
                }
            }
        }

        return tree;
    }
}
